package com.qf.data.filter;

import com.qf.common.model.DeviceModelValue;
import com.qf.common.utils.JsonUtil;
import com.qf.data.service.DeviceModelValueService;
import com.qf.data.service.HeartBeatService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 接收mq队列中传感器上报的数据, 并存储到mongodb中
 * @author 千锋健哥
 */
@Component
@Slf4j
public class DeviceValueListener {

    @Autowired
    private DeviceModelValueService deviceModelValueService;

    @Autowired
    private HeartBeatService heartBeatService;

    @RabbitHandler
    @RabbitListener(queues = "qf.queue.value.device")
    public void messageHandler(Channel channel, Message message, DeviceModelValue deviceModelValue) {

        try {
            log.info("[center-data数据中心]接收到的消息为:" + JsonUtil.toJsonString(deviceModelValue));
            //调用service保存数据到mongodb
            deviceModelValueService.saveModelValueToMongo(deviceModelValue);

            //接收心跳数据
            heartBeatService.saveHeartBeat(deviceModelValue.getProduct_key(), deviceModelValue.getDevice());
            //手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
